package com.fly.flowdemo.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;

import com.fly.flowdemo.R;

/**
 * Created with Android Studio.
 * Package_Name：com.fly.flowdemo.view
 * Project_Name：FlowDemo
 * User：郭鹏飞
 * Date：2015/12/9
 * Email：love518420@foxmail.com
 * Description：
 */
public class ButtonFlowLayout extends FlowLayout {

    private OnItemClickListener listener;

    private int resid;

    public ButtonFlowLayout(Context context) {
        this(context, null);
    }

    public ButtonFlowLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ButtonFlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray typedArray = context.obtainStyledAttributes(attrs,
                R.styleable.ButtonFlowLayout, defStyleAttr, 0);
        int count = typedArray.getIndexCount();
        for (int i = 0; i < count; i++) {
            int index = typedArray.getIndex(i);
            switch (index) {
                case R.styleable.ButtonFlowLayout_itemBackground:
                    resid = typedArray.getResourceId(index, -1);
                    break;
            }
        }
        typedArray.recycle();
    }

    /**
     * 设置标签
     *
     * @param labels String数组
     */
    public void setLabels(String[] labels) {
        if (labels == null || labels.length == 0) {
            throw new NullPointerException("标签为空");
        }
        for (int i = 0; i < labels.length; i++) {
            final Button button = new Button(context);
            button.setText(labels[i]);
            if (resid != -1) {
                button.setBackgroundResource(resid);
            }
            final int position = i;
            button.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (listener != null) {
                        listener.onItemClick(button, position);
                    }
                }
            });
            addView(button);
        }
    }

    /**
     * 为每一个item添加点击事件
     *
     * @param listener 点击事件回调
     */
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    public interface OnItemClickListener {
        /**
         * 点击事件的回调
         *
         * @param view     当前被点击的view
         * @param position 当前被点击的view的位置
         */
        void onItemClick(View view, int position);
    }

}
